package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 通过code获取openId
        String openid = getOpenId(userLoginDTO.getCode());

        // 根据openId查询用户信息
        User user = loadUserByOpenId(openid);

        // 生成SpringSecurity的通过认证标识
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        // 放到SpringSecurity的上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        return user;
    }

    /**
     * 根据code获取openid进行登录
     *
     * @param openId
     * @return
     */
    @Override
    public User loadUserByOpenId(String openId) {
        User user = userMapper.getByOpenid(openId);
        // 判断是否是新用户
        if (ObjectUtils.isEmpty(user)) {
            user = User
                    .builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 通过code获取openId
     *
     * @param code
     * @return
     */
    private String getOpenId(String code) {
        // 调用微信接口获取openId
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        // 拼接入参
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        // 发起请求
        String json = HttpClientUtil.doGet(url, map);

        // 解析出参获取openId和sessionKey
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        if (!StringUtils.hasText(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return openid;
    }
}
